package com.example.business.controller;


import com.example.business.dao.dto.ArticleDTO;
import com.example.business.dao.dto.NewsDTO;
import com.example.business.dao.NewsDetailDTO;
import com.example.business.dao.dto.DiarySubmitDTO;
import com.example.business.dao.entity.ArticleDetails;
import com.example.business.dao.entity.Plan;
import com.example.business.dao.mapper.ArticleDetailsMapper;
import com.example.oauthresourceserver.business.dao.entity.*;
import com.example.oauthresourceserver.business.dao.mapper.*;
import com.example.business.service.ArticleService;
import com.example.business.service.DiaryService;
import com.example.business.service.NewsService;
import com.example.business.service.PlanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.List;

@Slf4j
@CrossOrigin("*")
@RestController
@RequiredArgsConstructor
public class WriteController {
    private final DiaryService diaryService;
    private final ArticleService articleService;
    private final NewsService newsService;
    private final PlanService planService;

    @Autowired
    private ArticleDetailsMapper articleDetailsMapper;

    /**
     * 写日记（保存或更新当天日记）
     * 前端传递参数：content（日记内容）、weather（天气）
     */
    @PostMapping("/write/one")
    public ResponseEntity<String> writeDown(@RequestBody DiarySubmitDTO dto) {
        return diaryService.writeDown(dto);
    }

    /**
     * 查看过去的日记（默认查询最近7天）
     * 返回格式：[日期 天气：内容, ...]
     */
    @GetMapping("/get/somedays")
    public ResponseEntity<List<String>> someDays() {
        try {
            return ResponseEntity.ok(diaryService.someDays());
        } catch (Exception e) {
            log.error("获取历史日记失败", e);
            return ResponseEntity.status(500).body(Collections.emptyList());
        }
    }


    /**
     * 获取今日计划
     */
    @GetMapping("/day/plan")
    public ResponseEntity<String> getPlan() {
        try {
            Plan plan = planService.getPlan();
            // 若没有今日计划，返回空字符串（前端可判断是否显示输入框）
            System.out.println(plan);
            return ResponseEntity.ok(plan != null ? plan.getContent() : "");
        } catch (Exception e) {
            log.error("获取今日计划失败", e);
            return ResponseEntity.status(500).body("获取计划失败");
        }
    }

    /**
     * 保存/修改今日计划
     * 前端传递参数：request（计划内容，多行文本）
     */
    @PostMapping("/update/plan")
    public ResponseEntity<String> savePlan(@RequestParam("request") String planContent) {
        try {
            planService.savePlan(planContent);
            return ResponseEntity.ok("今日计划保存成功！");
        } catch (Exception e) {
            log.error("保存计划失败", e);
            return ResponseEntity.status(500).body("保存计划失败：" + e.getMessage());
        }
    }


    /**
     * 获取今日推荐文章（取最新发布的1篇）
     * 返回格式：标题\n摘要...
     */
    @GetMapping("/day/article")
    public ResponseEntity<ArticleDTO> getArticle() {
        try {
            return ResponseEntity.ok(articleService.getArticle());
        } catch (Exception e) {
            log.error("获取推荐文章失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }


    /**
     * 获取文章详情（需传递文章ID）
     */
    @GetMapping("/article/details")
    public ResponseEntity<String> getArticleDetails(@RequestParam("articleId") Long articleId) {
        try {
            ArticleDetails details = articleDetailsMapper.selectByArticleId(articleId);
            if (details == null) {
                return ResponseEntity.status(404).body("文章不存在");
            }
            return ResponseEntity.ok(details.getContent());
        } catch (Exception e) {
            log.error("获取文章详情失败", e);
            return ResponseEntity.status(500).body("获取详情失败");
        }
    }


    /**
     * 获取今日推荐新闻（取最新发布的2条）
     */
    @GetMapping("/day/news")
    public ResponseEntity<List<NewsDTO>> getNews() {
        try {
            return ResponseEntity.ok(newsService.getNews());
        } catch (Exception e) {
            log.error("获取推荐新闻失败", e);
            return ResponseEntity.status(500).body(Collections.emptyList());
        }
    }

    /**
     * 获取新闻详情（需传递新闻ID）
     */
    @GetMapping("/day/newsDetails")
    public ResponseEntity<NewsDetailDTO> getNewsDetails(@RequestParam("newsId") Long newsId) {
        try {
            return ResponseEntity.ok(newsService.getNewsDetails(newsId));
        } catch (Exception e) {
            log.error("获取新闻详情失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }


    // 工具方法：随机生成天气（兼容Java 8，使用Arrays.asList）
    private String getRandomWeather() {
        List<String> weathers = Arrays.asList("晴", "多云", "小雨", "阴", "雷阵雨");
        return weathers.get((int) (Math.random() * weathers.size()));
    }
}
